package com.tkx.dxb.service.base.handler;

import com.tkx.dxb.common.base.result.R;
import com.tkx.dxb.common.base.result.ResultCodeEnum;
import com.tkx.dxb.common.base.util.ExceptionUtils;
import com.tkx.dxb.service.base.exception.DxbException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author : victor
 * @since : 2020/10/30
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 异常处理器
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e){
//        e.printStackTrace();
        log.error(ExceptionUtils.getMessage(e));
        return R.error();
    }

    /**
     * BadSqlGrammarException spring JDBC封装的错误抛出
     */
    @ExceptionHandler(BadSqlGrammarException.class)
    @ResponseBody
    public R error(BadSqlGrammarException e){
        log.error(ExceptionUtils.getMessage(e));
        return R.setResult(ResultCodeEnum.BAD_SQL_GRAMMAR);
    }


    /**
     * HttpMessageNotReadableException http请求封装异常抛出错误
     */
    @ExceptionHandler(DxbException.class)
    @ResponseBody
    public R error(DxbException e){
        log.error(ExceptionUtils.getMessage(e));
        return R.error().message(e.getMessage()).code(e.getCode());
    }
}
